import { wxlogin, getInfo } from '../../services/profile'
import Toast from '@vant/weapp/toast/toast';

const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    confirmRead: false,
    showDialogAlert: false,
    dialogMsg:"",
    code:"",
    confirmNext: false,
    loginSuccess: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  onShow(){
    const token = wx.getStorageSync('token')
    if(token){
      wx.switchTab({
        url: '/pages/home-page/home-page',
      })
    }
  },

  onChange(){
    let confirmRead = !this.data.confirmRead
    this.setData({
      confirmRead
    })
  },

  handClick(){
    console.log("微信一键登录!!!>>>", this.data.confirmRead)
    if(!this.data.confirmRead){
      this.setData({
        showDialogAlert: true,
        dialogMsg:"请先阅读并同意协议!",
        confirmNext:false
      })
    }else{
      wx.login({
        success: res => {
          console.log("profile>loginRes>>>", res)
          wx.setStorageSync('code', res.code)
          this.setData({
            code: res.code,
            confirmNext:true
          })
        }
      })
    }
  },

  getPhoneNumber (e) {
    console.log("e>>>",e)
    const code = wx.getStorageSync('code') || ""
    const encryptedData = e.detail.encryptedData
    const iv = e.detail.iv
    
    wxlogin({code, encryptedData, iv, type:"1"}).then(res => {
      console.log("loginRes>>>",res)
      if(res.code === 200){
        if(!res.data){
          wx.reLaunch({
            url: '/pages/no-login-permission/no-login-permission',
          })
        }else {
          const token = res.data.access_token
          wx.setStorageSync('token', token)
          getInfo().then(InfoRes=>{
            console.log("InfoRes>>>", InfoRes)
            if(InfoRes.code === 200){
              wx.setStorageSync('userInfo', InfoRes.user)
              app.globalData.userInfo = InfoRes.user
              this.setData({
                confirmNext: false
              })
              wx.switchTab({
                url: '/pages/home-page/home-page',
              })
            }
          })
        }
      }
    })
  },

  handleStartClick(){
    console.log("确认OK")
    wx.switchTab({
      url: '/pages/home-page/home-page',
    })
  },

  navToPolicy(){
    wx.navigateTo({
      url: '/pages/policy-agreement/policy-agreement?type=policy',
    })
  },

  navToAgreement(){
    wx.navigateTo({
      url: '/pages/policy-agreement/policy-agreement?type=agreement',
    })
  }
  
})